package com.example.plat.security;

import com.example.plat.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class DbUserDetailService implements UserDetailsService {

    @Autowired
    UserService service;

    private static com.example.plat.enity.User u;

    public static com.example.plat.enity.User getU() {
        return u;
    }

    //创建一个UserDetails，返回用户及其权限信息，供认证和授权管理器使用
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        u = service.findUser(username);
        if(u == null) {
            throw new UsernameNotFoundException("用户"+username +"不存在");
        }

        return User.builder()
                .username(u.getUserName())
                .password(new BCryptPasswordEncoder().encode(u.getPassword()))
                .authorities("user")
                .build();
    }
}
